<template>
  <!-- 物资消耗编辑页 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="消耗明细"
          name="planDetail"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
                <BillTop title="物资消耗编辑" @cancel="cancel"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                    <el-form :model="basicFormData" label-width="150px"  :rules="rules"
                    ref="basicFormData"
                    class="demo-ruleForm">
                    <el-row>
                        <el-col :span="12">
                             <el-form-item label="消耗编号：">
                            {{basicFormData.billNo}}
                        </el-form-item>

                        </el-col>
                        <el-col :span="12">
                             <el-form-item label="机构：">
                            {{basicFormData.orgName}}
                        </el-form-item>

                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                             <el-form-item label="业务类型：" prop="businessType" v-if="basicFormData.businessType === 4 || basicFormData.businessType === 5 ">
                                    <el-select v-model="basicFormData.businessType"  @change="ValChange" placeholder="请选择业务类型" v-if="basicFormData.redBillState !='3' ">
                                        <el-option
                                        v-for="item in businessTypeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                        </el-option>
                                    </el-select>
                                    <span  v-else>{{basicFormData.businessType}}</span>
                                     <el-button v-if="basicFormData.redBillState !='3' " type="primary" style="background: #2e61d7;margin-left:5px" @click="selectData">选择明细</el-button>
                                    </el-form-item>
                            <el-form-item label="分包商：" v-if="basicFormData.businessType === 1 || basicFormData.businessType === 2 || basicFormData.businessType === 3 || basicFormData.businessType === 6 ||basicFormData.businessType === 7">
                                  <el-input
                                        v-model="basicFormData.subcontractorName"
                                         v-if="basicFormData.redBillState !='3' "
                                    >
                                    </el-input>
                                     <span  v-else>{{basicFormData.subcontractorName}}</span>

                        </el-form-item>

                        </el-col>
                        <el-col :span="12">
                             <el-form-item label="消耗日期：" prop="consumeDate">
                            <el-date-picker
                            v-model="basicFormData.consumeDate"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                            :clearable="false"
                            v-if="basicFormData.redBillState !='3' "
                            >
                            </el-date-picker>
                             <span  v-else>{{basicFormData.consumeDate}}</span>
                        </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="业务类型：" prop="businessType" v-if="basicFormData.businessType === 1 || basicFormData.businessType === 2 || basicFormData.businessType === 3 || basicFormData.businessType === 6 ||basicFormData.businessType === 7">
                                    <el-select v-model="basicFormData.businessType" @change="ValChange" placeholder="请选择业务类型"  v-if="basicFormData.redBillState !='3' ">
                                        <el-option
                                        v-for="item in businessTypeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                        </el-option>
                                    </el-select>
                                     <span  v-else>{{basicFormData.businessType}}</span>
                                     <el-button  type="primary" style="background: #2e61d7;margin-left:5px" @click="selectData"  v-if="basicFormData.redBillState !='3' ">选择明细</el-button>
                                    </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="加工单位：" v-if="basicFormData.businessType === 2 || basicFormData.businessType === 6">
                                        {{basicFormData.processingUnitName}}
                                    </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                               <el-form-item label="录入人：" v-if="basicFormData.businessType === 5">
                                        {{basicFormData.recorderName}}
                                    </el-form-item>
                        <el-form-item label="消耗金额（元）："  v-if="basicFormData.businessType === 1 || basicFormData.businessType === 2 || basicFormData.businessType === 3 || basicFormData.businessType === 4 || basicFormData.businessType === 6 ||basicFormData.businessType === 7">
                          {{basicFormData.consumptionAmount}}
                        </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="录入人：" v-if="basicFormData.businessType === 1 || basicFormData.businessType === 2 || basicFormData.businessType === 3 || basicFormData.businessType === 4 ||basicFormData.businessType === 7">
                                        {{basicFormData.recorderName}}
                                    </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                        <el-form-item label="状态：">
                        {{ '草稿' }}
                        </el-form-item>
                        </el-col>
                        <el-col :span="12">

                        </el-col>
                    </el-row>

                    <el-row>
                        <el-form-item label="备注：">
                        <el-input
                            type="textarea"
                            :rows="2"
                            placeholder="请输入内容"
                            v-model="basicFormData.remarks"
                        >
                        </el-input>
                        </el-form-item>
                    </el-row>
                    <el-row>
                          <!-- 发生冲红单业务时，才显示 -->
                            <el-form-item label="冲红单：" v-if="basicFormData.redBillId != null &&basicFormData.redBillNo != null &&basicFormData.redBillState != ''">
                                  <span
                                      :style="
                                          redBillStateStyle
                                      "
                                      >{{
                                          redBillStateFun
                                      }}</span
                                  >
                              </el-form-item>
                      </el-row>
                    </el-form>
      </div>
              </div>
            </div>
          </div>

          <!-- 消耗明细 -->
          <div id="planDetailCon" class="con" v-if="basicFormData.businessType !== 4">
            <div class="tabs-title" id="planDetail">消耗明细</div>
            <el-tabs
              :class="'childTab ' + childTabClass"
              tab-position="left"
              v-model="tabsNameChild"
              @tab-click="onChangeTab"
            >
              <el-tab-pane
                label="物资明细"
                name="materialDetails"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <el-tab-pane
                label="加工成品明细"
                name="technicalParameter"
                :disabled="clickTabFlag"
                v-if="basicFormData.businessType===2 || basicFormData.businessType ===6"
              ></el-tab-pane>
              <div>
                <div id="planDetailCon">
                  <div class="tabs-title" id="materialDetails">
                    物资明细
                  </div>
                  <div class="e-table">
                            <div class="errorMsg" v-if="errorMsg.length > 0">
                        <span v-for="(item, index) in errorMsg" :key="index">
                        {{ item }}
                        </span>
                    </div>
                    <el-table
                    class="table"
                      :data="materialsDetailsList"
                      border
                      style="width: 100%"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                     :row-class-name="tableRowClassName"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                       :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren',
                             }"
                       row-key="uuid"
                       :max-height="$store.state.tableHeight"
                       ref="table"
                       v-sortTable="{ 'tableData': materialsDetailsList, '_this': this, 'ref': 'table' }"
                    >
                  <el-table-column
                    fixed
                    type="index"
                    label="序号"
                    width="80"
                    align="center"
                  >
                </el-table-column>
                <!-- <el-table-column fixed label="操作" width="70">
                  <template slot-scope="{ row, $index }">
                    <div class="handle">
                      <div style="cursor: pointer">
                        <img
                          src="@/assets/btn/delete.png"
                          @click="handleDelete(row, $index)"
                          v-if="$index > 0"
                        />
                      </div>
                    </div>
                  </template>
                </el-table-column> -->
                      <el-table-column
                        prop="materialClassName"
                        label="物资类别"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="spec"
                        label="规格"
                        width="100"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="texture"
                        label="材质"
                        width="100"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="unit"
                        label="单位"
                        width="100"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="warehouseName"
                        label="仓库"
                        width="100"
                        v-if="basicFormData.businessType !==5"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="contractName"
                        label="合同名称"
                        width="100"
                        v-if="basicFormData.businessType !==5 &&basicFormData.businessType !==3"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="subItemName"
                        label="分部分项"
                        width="100"
                         v-if="basicFormData.businessType !==5 &&basicFormData.businessType !==3"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="designQuantity"
                        label="设计数量"
                        width="100"
                         v-if="basicFormData.businessType !==5"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="consumeQuantity"
                        label="消耗数量"
                        width="100"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="cumulativeConsumeQuantity"
                        label="累计消耗数量"
                        width="150"
                         v-if="basicFormData.businessType !==5"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="consumePrice"
                        label="消耗单价（元）"
                        width="150"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="consumeAmount"
                        label="消耗金额（元）"
                        width="150"
                         v-if="basicFormData.businessType !==5"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="issueType"
                        label="甲供/发料类型"
                        width="150"
                         v-if="basicFormData.businessType === 1 || basicFormData.businessType === 7"
                      >
                      <template slot-scope="{ row }" >
                      <!-- <el-select v-model="row.partyAType" placeholder="请选择" v-if="$index > 0 && basicFormData.redBillState != '3'" @change="selectPartyAType(row)">
                          <el-option
                            v-for="item in procurementMethod"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                    </el-select> -->
                    <span>{{['','工程消耗','研发支出','安全环保支出'][row.issueType]}}</span>

                    </template>
                      </el-table-column>
                      <el-table-column
                        prop="issueType"
                        label="甲供/发料类型"
                        width="150"
                         v-if="basicFormData.businessType === 2 || basicFormData.businessType === 6"
                      >
                      <template slot-scope="{ row ,$index }" >
                    <span v-if="$index > 0">{{['','工程消耗','研发支出','安全环保支出'][row.issueType]}}</span>
                    </template>
                      </el-table-column>
                      <el-table-column
                        prop="issueType"
                        label="甲供/发料类型"
                        width="150"
                         v-if="basicFormData.businessType === 3"
                      >
                      <template slot-scope="{ $index }">
                    <span v-if="$index > 0">{{'销售消耗'}}</span>
                    </template>
                      </el-table-column>
                       <el-table-column
                        prop="issueType"
                        label="甲供/发料类型"
                        width="150"
                         v-if="basicFormData.businessType === 4"
                      >
                       <template slot-scope="{ $index }">
                    <span v-if="$index > 0">{{'销售消耗'}}</span>
                    </template>
                      </el-table-column>
                      <el-table-column
                        prop="issueType"
                        label="甲供/发料类型"
                        width="150"
                         v-if="basicFormData.businessType === 5"
                      >
                      <template slot-scope="{ $index }">
                    <span v-if="$index > 0">{{'机械消耗'}}</span>
                    </template>
                      </el-table-column>
                      <el-table-column
                        prop="consumeType"
                        label="消耗类型"
                        width="100"
                         v-if="basicFormData.businessType !==5"
                      >
                       <template slot-scope="{ row }" >
                            <span >{{['甲供','超甲供扣款','非甲供扣款'][row.consumeType]}}</span>
                            </template>
                      </el-table-column>
                       <el-table-column
                        v-if="basicFormData.businessType === 1 || basicFormData.businessType === 2 &&basicFormData.businessType !==5 ||basicFormData.businessType === 7"
                        prop="deductionQuantity"
                        label="扣款数量"
                        width="100"
                      >
                      </el-table-column>
                       <el-table-column
                       v-if="basicFormData.businessType === 1 || basicFormData.businessType === 2 &&basicFormData.businessType !==5 ||basicFormData.businessType === 7"
                        prop="deductionAmount"
                        label="扣款金额（元）"
                        width="150"
                      >
                      </el-table-column>
                       <el-table-column
                       v-if="basicFormData.businessType === 5"
                        prop="originalConsumptionAmountVarianceAdjustment"
                        label="调差原消耗金额（元）"
                        width="150"
                      >
                      </el-table-column>
                       <el-table-column
                       v-if="basicFormData.businessType === 5"
                        prop="amountAfterVarianceAdjustment"
                        label="调差后金额（元）"
                        width="150"
                      >
                      </el-table-column>

                    </el-table>

                  </div>
                </div>
              <!--  加工成品明细   -->
                <div id="planDetailCon" v-if="basicFormData.businessType===2 || basicFormData.businessType ===6">
                  <div class="tabs-title" id="technicalParameter">加工成品明细</div>
                  <div class="e-table">
                    <div class="errorMsg" v-if="errorMsg.length > 0">
                            <span v-for="(item, index) in errorMsg" :key="index">
                            {{ item }}
                            </span>
                        </div>
                    <el-table
                    class="table"
                      :data="processDetailsList"
                      border
                      style="width: 100%"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren',
                             }"
                       row-key="uuid"
                       :max-height="$store.state.tableHeight"
                       ref="table"
                v-sortTable="{ 'processDetailsList': tableData, '_this': this, 'ref': 'table' }"
                    >
                      <el-table-column prop="materialClassName" label="物资类别" width="150">
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column prop="spec" label="规格" width="100">
                      </el-table-column>
                      <el-table-column prop="texture" label="材质" width="100">
                      </el-table-column>
                      <el-table-column prop="unit" label="单位" width="100">
                      </el-table-column>
                      <el-table-column prop="warehouseName" label="仓库" width="100">
                      </el-table-column>
                      <el-table-column prop="consumeQuantity" label="消耗数量" width="100">
                         <template slot-scope="{ row, $index }">
                            <el-input
                            v-enter-float="{
                                    set: row,
                                    key: 'consumeQuantity'
                                }"
                            @input="input(row)"
                            @blur="totalconsumeAmount2"
                            v-model="row.consumeQuantity"
                            clearable
                            v-if="$index > 0"
                            ></el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="cumulativeConsumeQuantity" label="累计消耗数量" width="150">
                      </el-table-column>
                       <el-table-column prop="consumePrice" label="消耗单价（元）" width="150">
                      </el-table-column>
                       <el-table-column prop="consumeAmount" label="消耗金额（元）" width="150">
                      </el-table-column>
                    </el-table>

                  </div>
                </div>
              </div>
            </el-tabs>
          </div>

          <!-- 业务类型为机械发料显示 -->
          <div id="planDetailCon" class="con" v-if="basicFormData.businessType === 4">
            <div class="tabs-title" id="planDetail">消耗明细</div>
            <el-tabs
              :class="'childTab ' + childTabClass"
              tab-position="left"
              v-model="tabsNameChild"
              @tab-click="onChangeTab"
            >
              <el-tab-pane
                label="物资明细"
                name="materialDetails"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <el-tab-pane
                label="汇总查看"
                name="technicalParameter"
                :disabled="clickTabFlag"
              ></el-tab-pane>
              <div>
                <div id="planDetailCon">
                  <div class="tabs-title" id="materialDetails">
                    物资明细
                  </div>
                  <div class="e-table">
                    <div class="errorMsg" v-if="errorMsg.length > 0">
                            <span v-for="(item, index) in errorMsg" :key="index">
                            {{ item }}
                            </span>
                        </div>
                    <el-table
                    class="table"
                      :data="EquipDtls"
                       border
                      style="width: 100%"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :row-class-name="tableRowClassName"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      ref="table"
                v-sortTable="{ 'tableData': EquipDtls, '_this': this, 'ref': 'table' }"
                    >
                     <el-table-column
                        fixed
                        type="index"
                        label="序号"
                        width="80"
                        align="center"
                      >
                     </el-table-column>
                      <!-- <el-table-column fixed label="操作" width="70">
                        <template slot-scope="{ row, $index }">
                          <div class="handle">
                            <div style="cursor: pointer">
                              <img
                                src="@/assets/btn/delete.png"
                                @click="handleDelete(row, $index)"
                              />
                            </div>
                          </div>
                        </template>
                      </el-table-column> -->
                      <el-table-column
                        prop="equipNo"
                        label="设备编号"
                        min-width="150"
                      >
                       <template slot-scope="scope">
                          <span
                            @click="clickEquipNo(scope.row)"
                            style="color: blue; cursor: pointer"
                          >
                            {{ scope.row.equipNo }}
                          </span>
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="equipName"
                        label="设备名称"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="spec"
                        label="规格型号"
                        width="100"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="consumeAmount"
                        label="消耗金额（元）"
                        width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="remarks"
                        label="备注"
                        width="100"
                      >
                      </el-table-column>

                    </el-table>

                  <!--设备子列表  -->
                 <el-table
                      class="table"
                      v-if="tableShow"
                      :data="equipSonTable"
                      border
                      style="width: 100%;  margin-top: 20px;"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :row-class-name="tableRowClassName"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                       :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren',
                        }"
                        row-key="uuid"
                        :max-height="$store.state.tableHeight"
                        ref="table"
                v-sortTable="{ 'tableData': equipSonTable, '_this': this, 'ref': 'table' }"
                    >
                    <el-table-column
                        fixed
                        type="index"
                        label="序号"
                        width="80"
                        align="center"
                      >
                     </el-table-column>
                      <!-- <el-table-column fixed label="操作" width="70">
                        <template slot-scope="{ row, $index }">
                          <div class="handle">
                            <div style="cursor: pointer">
                              <img
                                src="@/assets/btn/delete.png"
                                @click="handleDelete(row, $index)"
                                 v-if="$index > 0"
                              />
                            </div>
                          </div>
                        </template>
                      </el-table-column> -->
                      <el-table-column
                        prop="materialClassName"
                        label="物资类别"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="spec"
                        label="规格"
                        width="100"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="texture"
                        label="材质"
                        width="100"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="unit"
                        label="单位"
                        width="100"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="consumeQuantity"
                        label="消耗数量"
                        width="100"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="cumulativeConsumeQuantity	"
                        label="累计消耗数量"
                        width="150"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="consumePrice"
                        label="消耗单价（元）"
                        width="150"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="consumeAmount"
                        label="消耗金额（元）"
                        width="150"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="issueType"
                        label="甲供/发料类型"
                        width="150"
                      >
                     </el-table-column>
                      <el-table-column
                        prop="consumeType"
                        label="消耗类型"
                        width="100"
                      >
                      </el-table-column>

                    </el-table>

                  </div>
                </div>
              <!--  汇总查看   -->
                <div id="planDetailCon">
                  <div class="tabs-title" id="technicalParameter">汇总查看</div>
                  <div class="e-table">
                    <el-table
                    class="table"
                      :data="collectExamineList"
                      border
                      style="width: 100%"
                      @cell-mouse-enter="cellMouseEnter"
                      @cell-mouse-leave="cellMouseLeave"
                      :cell-class-name="cellClsNm"
                      :header-cell-style="{ textAlign: 'center' }"
                      :cell-style="{ textAlign: 'center' }"
                      :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren',
                             }"
                       row-key="uuid"
                       :max-height="$store.state.tableHeight"
                       ref="table"
                v-sortTable="{ 'tableData': collectExamineList, '_this': this, 'ref': 'table' }"
                    >
                      <el-table-column prop="" label="物资类别" width="150">
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="150"
                      >
                      </el-table-column>
                      <el-table-column prop="spec" label="规格" width="100">
                      </el-table-column>
                      <el-table-column prop="texture" label="材质" width="100">
                      </el-table-column>
                      <el-table-column prop="unit" label="单位" width="100">
                      </el-table-column>
                      <el-table-column prop="designQuantity" label="设计数量" width="100">
                      </el-table-column>
                      <el-table-column prop="consumeQuantity" label="消耗数量" width="100">
                      </el-table-column>
                      <el-table-column prop="cumulativeConsumeQuantity" label="累计消耗数量" width="150">
                      </el-table-column>
                       <el-table-column prop="consumePrice" label="消耗单价（元）" width="150">
                      </el-table-column>
                       <el-table-column prop="consumeAmount" label="消耗金额（元）" width="150">
                      </el-table-column>
                       <el-table-column prop="issueType" label="发料类型" width="150">
                      </el-table-column>
                       <el-table-column prop="consumeType" label="消耗类型" width="150">
                      </el-table-column>
                    </el-table>

                  </div>
                </div>
              </div>
            </el-tabs>
          </div>

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="material"
              v-if="objFlag.flag5"
            />
            <div class="seize-a-seat" v-else>
              <i class="el-icon-loading"></i>
            </div>
          </div>
          <!-- 审核历史 -->
            <div id="auditHistoryCon" class="con">
                <div class="tabs-title" id="auditHistory">审核历史</div>
                <div class="e-table">
                    <ComAuditHistoryIndex
                        :tableData.sync="auditHistoryTable"
                        @getAuditHistory="getAuditHistory"
                        ref="AuditHistoryRef"
                    />
                </div>
              </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
      <span class="tip"
        ><span style="color: red; margin-right: 0">*</span>为必填项</span
      >
      <el-button
          type="primary"
          style="background: #2e61d7"
          v-debounce
          v-if="basicFormData.state === '1'"
          >打印</el-button
      >
       <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />

      <!-- <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        @click="save('basicFormData')"
        v-debounce
        >保存</el-button
      >
      <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        @click="submit('basicFormData')"
        v-debounce
        >保存并提交</el-button
      >
       <el-button
        type="primary"
        style="background: #2e61d7"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="undoAudit"
        >撤回</el-button
      >
      <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="nullify()"
        >作废</el-button
          >
      <el-button
        type="danger"
        size="small"
       class="btn-delete"
        @click="ctDelete"
        v-if="basicFormData.state === '0'"
        v-debounce
        >删除</el-button
      > -->
      <el-button size="small" @click="cancel">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import {  getUuid, selectDataClient, openAppClient } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import Api from '@/api/materials/consumptionMaterials.js'
import CommonApi from '@/api/materials/common.js'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            auditState: {}, //按钮状态
            businessTypeList: [{
                value: 1,
                label: '消耗盘点(事实合同)'
            }, {
                value: 2,
                label: '加工发料'
            }, {
                value: 3,
                label: '销售消耗'
            }, {
                value: 4,
                label: '机械发料'
            }, {
                value: 5,
                label: '账面调差'
            },
            {
                value: 6,
                label: '加工销售消耗'
            },
            {
                value: 7,
                label: '消耗盘点'
            }
            ],
            EquipDtls: [], //设备明细
            materialsDetailsList: [], //物资明细
            processDetailsList: [], //加工成品明细
            equipSonTable: [], //设备子列表
            collectExamineList: [], //汇总查看
            auditHistoryTable: [], //审核历史
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            planSelect: [],
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            MouseEnterId: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'baseCurConsumptionAmount': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'businessType': null,
                'consumeDate': '',
                'consumptionAmount': 0,
                'consumptionQuantity': 0,
                'currency': '',
                'currencyId': '',
                'easId': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isRed': null,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'processingUnitId': '',
                'processingUnitName': '',
                'recorderId': '',
                'recorderName': '',
                'remarks': '',
                'rmbConsumptionAmount': 0,
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'sourceId': '',
                'sourceNumber': '',
                'state': '',
                'subcontractorId': '',
                'subcontractorName': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            params: {
                billId: this.$route.query.billid, //单据Id  ***
                billType: '1027', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: this.orgId, //单据机构Id
                orgName: this.orgName, //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            billid: '',
            isSkip: false, //是否跳转
            show: false, //申报机构子列表
            showTwo: false,
            dtlIds: '', //
            billIdArr: [],
            OrgAllData: [],
            consumePrice: 0,
            masterPlanBillId: '',
            procurementMethod: [{
                value: 1,
                label: '工程消耗'
            }, {
                value: 2,
                label: '研发支出'
            }, {
                value: 3,
                label: '安全环保支出'
            }],
            data: [],
            //验证
            rules: {
                consumeDate: [
                    {  required: true, message: '请选择消耗日期', trigger: 'change' }
                ],
                businessType: [
                    {  required: true, message: '请选择业务类型', trigger: 'change' }
                ],

            },
            tableShow: false,
            UidArr: [],
            Uids: 1,
            Id: '',
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1027,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.founderId = localStorage.getItem('userId')
        this.userId = localStorage.getItem('userId')
        this.billid = this.$route.query.billid
        this.getBasicData() //基本信息数据
        this.getEquipDtlsById() //设备明细
        this.getRawMaterialsListById() //
        this.getFinishedGoodsListById()//成品物资
        this.getAttach() //附件
        this.getCurrentUnitInfo()
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),

        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1027,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.cancel, null, this.cancel)
                })
            })
        },
        //撤回
        undoAudit () {
            const params2 = {
                billId: this.billid, //单据Id  ***
                billType: '1027', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: '', //单据机构Id
                orgName: '', //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            }
            CommonApi.undoAudit(params2).then(() => {
                this.clientPop('suc', '撤回成功！', this.cancel, null, this.cancel)
            })
        },
        //选择甲供类型
        selectPartyAType (row) {
            this.materialsDetailsList.forEach(item=>{
                item.children.forEach(a=>{
                    if(row.dtlId === a.dtlId) {
                        if(a.changeType === 1) {
                            a.changeType = 1
                        }else{
                            a.changeType = 2
                        }
                        a.issueType = row.issueType
                    }else if(a.changeType !== 2) {
                        a.changeType = 0
                    }
                })
            })
        },
        ValChange () {
            this.basicFormData.subcontractorId = ''
            this.basicFormData.subcontractorName = ''
        },
        //计算扣款数量和扣款金额
        deductionQuantityAndDeductionAmount () {
            this.materialsDetailsList.forEach(a=>{
                a.children.forEach(item=>{
                    //扣款数量 :消耗数量-设计数量 deductionQuantity
                    item.deductionQuantity = Number(item.consumeQuantity) - Number(item.designQuantity)
                    item.deductionQuantity = item.deductionQuantity.toFixed(2)
                    //扣款金额  扣款数量*消耗单价 deductionAmount
                    item.deductionAmount = Number(item.deductionQuantity) * Number(item.consumePrice)
                    item.deductionAmount = item.deductionAmount.toFixed(2)
                })
            })
        },
        //汇总消耗金额
        AllConsumptionAmount () {
            let num = 0
            this.materialsDetailsList.forEach(item=>{
                item.children.forEach(a=>{
                    if(a.consumeAmount > 0) {
                        num += Number(a.consumeAmount)
                    }
                })
            })
            this.basicFormData.consumptionAmount = num
            this.basicFormData.consumptionAmount = this.basicFormData.consumptionAmount.toFixed(2)
        },
        //汇总明细 累计消耗数量
        totalCumulativeConsumeQuantity () {
            let num = 0
            this.materialsDetailsList.forEach(item=>{
                item.children.forEach(a=>{
                    if(a.consumeQuantity > 0) {
                        num += Number(a.consumeQuantity)
                        a.cumulativeConsumeQuantity = num
                    }
                })
            })
        },
        //汇总加工成品的累计消耗数量
        totalCumulativeConsumeQuantity2 () {
            let num = 0
            this.processDetailsList.forEach(item=>{
                item.children.forEach(a=>{
                    if(a.consumeQuantity > 0) {
                        num += Number(a.consumeQuantity)
                        a.cumulativeConsumeQuantity = num
                    }
                })
            })
        },
        //计算加工成品的金额
        totalconsumeAmount2 () {
            let num = 0
            this.processDetailsList.forEach(a=>{
                console.log('a', a)
                a.children.forEach(b=>{
                    if(b.consumePrice > 0 || b.consumeQuantity > 0) {
                        b.consumeAmount = Number(b.consumePrice) * Number(b.consumeQuantity)
                        b.consumeAmount = b.consumeAmount.toFixed(2)
                        num += Number(b.consumeAmount)
                    }
                })
            })
            this.basicFormData.consumptionAmount = num
            this.basicFormData.consumptionAmount = this.basicFormData.consumptionAmount.toFixed(2)
        },
        //汇总消耗金额
        totalconsumeAmount () {
            console.log('this.materialsDetailsList', this.materialsDetailsList)
            let num = 0
            this.materialsDetailsList.forEach(a=>{
                console.log('a', a)
                a.children.forEach(b=>{
                    if(b.consumePrice > 0 || b.consumeQuantity > 0) {
                        b.consumeAmount = Number(b.consumePrice) * Number(b.consumeQuantity)
                        b.consumeAmount = b.consumeAmount.toFixed(2)
                        num += Number(b.consumeAmount)
                    }
                })
            })
            this.basicFormData.consumptionAmount = num
            this.basicFormData.consumptionAmount = this.basicFormData.consumptionAmount.toFixed(2)

        },
        //选择明细(根据业务类型)
        selectData () {
            if(this.basicFormData.businessType === 1) {
                let businessType = '2'
                this.consumeCheck(businessType)  //选择消耗盘点(事实合同)
            }else if(this.basicFormData.businessType === 2) {
                this.selectProcessReceiving()  //选择加工发料
            }else if(this.basicFormData.businessType === 3) {
                this.selectSalesConsumption() //选择销售消耗(现场发料)
            }else if(this.basicFormData.businessType === 4) {
                this.selectMechanicalStoreIssue()  //选择机械发料
            }else if(this.basicFormData.businessType === 5) {
                this.monthlySettlement()   //账面调差
            }else if(this.basicFormData.businessType === 6) {
                this.selectProcessSalesConsumption() //选择加工销售消耗
            }else if(this.basicFormData.businessType === 7) {
                //选择消耗盘点(分包合同)
                let businessType = '1'
                this.consumeCheck(businessType)
            }
        },

        //保存按钮
        save (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    console.log('11111', this.basicFormData.businessType)
                    if(this.basicFormData.businessType === 1) {  //选择消耗盘点
                        const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                        Promise.all([p1, p2]).then(() => {
                            this.clientPop('suc', '保存成功！', this.$router.go(0))
                        })
                    }else if(this.basicFormData.businessType === 2) { //选择加工发料
                        const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        const p2 = Api.updatematerialsList(this.materialsDetailsList) //物资
                        const p3 = Api.updateFinishedGoodsList(this.processDetailsList) //成品物资
                        Promise.all([p1, p2, p3]).then(() => {
                            this.clientPop('suc', '保存成功！', this.$router.go(0))
                        })
                    }else if(this.basicFormData.businessType === 3) { //销售消耗
                        const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                        Promise.all([p1, p2]).then(() => {
                            this.clientPop('suc', '保存成功！', this.$router.go(0))
                        })
                    }else if(this.basicFormData.businessType === 4) { //机械发料
                        const p1 = Api.EditConsumptionMaterials(this.basicFormData)
                        //保存设备物资明细
                        const p2 = Api.saveEquipDtls(this.EquipDtls)
                        //修改原物资明细(设备下子列表)
                        const p3 = Api.updatematerialsList(this.equipSonTable)
                        Promise.all([p1, p2, p3]).then(() => {
                            this.clientPop('suc', '保存成功！', this.$router.go(0))
                        })
                    }else if(this.basicFormData.businessType === 5) { //账面调差
                        const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                        Promise.all([p1, p2]).then(() => {
                            this.clientPop('suc', '保存成功！', this.$router.go(0))
                        })
                    }else if(this.basicFormData.businessType === 6) { //加工销售消耗
                        const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        const p2 = Api.updatematerialsList(this.materialsDetailsList) //物资
                        const p3 = Api.updateFinishedGoodsList(this.processDetailsList) //成品物资
                        Promise.all([p1, p2, p3]).then(() => {
                            this.clientPop('suc', '保存成功！', this.$router.go(0))
                        })
                    }else if(this.basicFormData.businessType === 7) {
                        const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                        Promise.all([p1, p2]).then(() => {
                            this.clientPop('suc', '保存成功！', this.$router.go(0))
                        })
                    }

                } else {
                    return false
                }
            })
        },
        //保存并提交
        submit (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if(this.basicFormData.businessType === 1) {  //选择消耗盘点
                        // const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        // const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                        // const p3 = CommonApi.AuditCommit(this.params)
                        // Promise.all([p1, p2, p3]).then(() => {
                        //     this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                        // })
                        return new Promise((resolve, reject) => {
                            this.verifyTable()
                                .then(() => {
                                    const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                                    const p2 = Api.updatematerialsList(this.materialsDetailsList)
                                    Promise.all([p1, p2]) .then(() => {
                                        CommonApi.AuditCommit(this.params)
                                            .then(() => {
                                                this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                                            })
                                            .catch(err => {
                                                this.setError('receivingMaterials')
                                                reject(err)
                                            })
                                        resolve()
                                    })
                                        .catch(err => {
                                            this.setError('receivingMaterials')
                                            reject(err)
                                        })
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        })
                    }else if(this.basicFormData.businessType === 2) { //选择加工发料
                        // const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        // const p2 = Api.updatematerialsList(this.materialsDetailsList) //物资
                        // const p3 = Api.updateFinishedGoodsList(this.processDetailsList) //成品物资
                        // const p4 = CommonApi.AuditCommit(this.params)
                        // Promise.all([p1, p2, p3, p4]).then(() => {
                        //     this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                        // })
                        return new Promise((resolve, reject) => {
                            this.verifyTable()
                                .then(() => {
                                    const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                                    const p2 = Api.updatematerialsList(this.materialsDetailsList)
                                    const p3 = Api.updateFinishedGoodsList(this.processDetailsList)
                                    Promise.all([p1, p2, p3]) .then(() => {
                                        CommonApi.AuditCommit(this.params)
                                            .then(() => {
                                                this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                                            })
                                            .catch(err => {
                                                this.setError('receivingMaterials')
                                                reject(err)
                                            })
                                        resolve()
                                    })
                                        .catch(err => {
                                            this.setError('receivingMaterials')
                                            reject(err)
                                        })
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        })
                    }else if(this.basicFormData.businessType === 3) { //销售消耗
                        // const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        // const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                        // const p3 = CommonApi.AuditCommit(this.params)
                        // Promise.all([p1, p2, p3]).then(() => {
                        //     this.clientPop('suc', '保存并提交成功！',  this.cancel, null, this.cancel)
                        // })
                        return new Promise((resolve, reject) => {
                            this.verifyTable()
                                .then(() => {
                                    const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                                    const p2 = Api.updatematerialsList(this.materialsDetailsList)
                                    Promise.all([p1, p2]) .then(() => {
                                        CommonApi.AuditCommit(this.params)
                                            .then(() => {
                                                this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                                            })
                                            .catch(err => {
                                                this.setError('receivingMaterials')
                                                reject(err)
                                            })
                                        resolve()
                                    })
                                        .catch(err => {
                                            this.setError('receivingMaterials')
                                            reject(err)
                                        })
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        })
                    }else if(this.basicFormData.businessType === 4) { //机械发料
                        // const p1 = Api.EditConsumptionMaterials(this.basicFormData)
                        // //保存设备物资明细
                        // const p2 = Api.saveEquipDtls(this.EquipDtls)
                        // //修改原物资明细(设备下子列表)
                        // const p3 = Api.updatematerialsList(this.equipSonTable)
                        // const p4 = CommonApi.AuditCommit(this.params)
                        // Promise.all([p1, p2, p3, p4]).then(() => {
                        //     this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                        // })
                        return new Promise((resolve, reject) => {
                            this.verifyTable()
                                .then(() => {
                                    const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                                    const p2 = Api.saveEquipDtls(this.EquipDtls) //明细
                                    const p3 = Api.updatematerialsList(this.equipSonTable)
                                    Promise.all([p1, p2, p3]) .then(() => {
                                        CommonApi.AuditCommit(this.params)
                                            .then(() => {
                                                this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                                            })
                                            .catch(err => {
                                                this.setError('receivingMaterials')
                                                reject(err)
                                            })
                                        resolve()
                                    })
                                        .catch(err => {
                                            this.setError('receivingMaterials')
                                            reject(err)
                                        })
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        })
                    }else if(this.basicFormData.businessType === 5) {
                        //账面调差
                        // const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        // const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                        // const p3 = CommonApi.AuditCommit(this.params)
                        // Promise.all([p1, p2, p3]).then(() => {
                        //     this.clientPop('suc', '保存并提交成功！',  this.cancel, null, this.cancel)
                        // })
                        return new Promise((resolve, reject) => {
                            this.verifyTable()
                                .then(() => {
                                    const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                                    const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                                    Promise.all([p1, p2]) .then(() => {
                                        CommonApi.AuditCommit(this.params)
                                            .then(() => {
                                                this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                                            })
                                            .catch(err => {
                                                this.setError('receivingMaterials')
                                                reject(err)
                                            })
                                        resolve()
                                    })
                                        .catch(err => {
                                            this.setError('receivingMaterials')
                                            reject(err)
                                        })
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        })
                    }else if(this.basicFormData.businessType === 6) {//加工销售消耗
                        // const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        // const p2 = Api.updatematerialsList(this.materialsDetailsList) //物资
                        // const p3 = Api.updateFinishedGoodsList(this.processDetailsList) //成品物资
                        // const p4 = CommonApi.AuditCommit(this.params)
                        // Promise.all([p1, p2, p3, p4]).then(() => {
                        //     this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                        // })
                        return new Promise((resolve, reject) => {
                            this.verifyTable()
                                .then(() => {
                                    const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                                    const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                                    Promise.all([p1, p2]) .then(() => {
                                        CommonApi.AuditCommit(this.params)
                                            .then(() => {
                                                this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                                            })
                                            .catch(err => {
                                                this.setError('receivingMaterials')
                                                reject(err)
                                            })
                                        resolve()
                                    })
                                        .catch(err => {
                                            this.setError('receivingMaterials')
                                            reject(err)
                                        })
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        })
                    }else if(this.basicFormData.businessType === 7) {  //选择消耗盘点
                        // this.verifyTable()
                        // const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                        // const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                        // const p3 = CommonApi.AuditCommit(this.params)
                        // Promise.all([p1, p2, p3]).then(() => {
                        //     this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                        // })
                        return new Promise((resolve, reject) => {
                            this.verifyTable()
                                .then(() => {
                                    const p1 = Api.EditConsumptionMaterials(this.basicFormData) //基础
                                    const p2 = Api.updatematerialsList(this.materialsDetailsList) //明细
                                    Promise.all([p1, p2]) .then(() => {
                                        CommonApi.AuditCommit(this.params)
                                            .then(() => {
                                                this.clientPop('suc', '保存并提交成功！', this.cancel, null, this.cancel)
                                            })
                                            .catch(err => {
                                                this.setError('receivingMaterials')
                                                reject(err)
                                            })
                                        resolve()
                                    })
                                        .catch(err => {
                                            this.setError('receivingMaterials')
                                            reject(err)
                                        })
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        })
                    }
                } else {
                    return false
                }
            })
        },
        //选择账面调差
        monthlySettlement () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/monthlySettlement/listUnconsumesMaterialForSelected', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(this.orgId),
                Title: '选择月结信息' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    if(this.materialsDetailsList.length > 0) {
                        val.forEach(e=>{
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            e.materialClassNameArr.shift()
                            e.materialClassIdArr.shift()
                            const obj = {
                                uuid: getUuid(),
                                customId: getUuid(),
                                'amountAfterVarianceAdjustment': 0, //调差后金额
                                'billId': this.billid, //物资消耗id
                                'changeType': 1, //变更类型
                                'consumeAmount': e.amount, //消耗金额(元)
                                'consumePrice': 0, //消耗单价(元)
                                'consumeQuantity': e.quantity, //消耗数量
                                'consumeType': 0, //消耗类型
                                'contractId': '', //合同id
                                'contractName': '', //合同名称
                                'cumulativeConsumeQuantity': '', //累计消耗数量
                                'deductionAmount': 0, //扣款金额(元)
                                'deductionQuantity': 0, //扣款数量
                                'designQuantity': 0, //设计数量
                                'dtlId': '', //物资消耗明细id
                                'finishedGoodsDtlId': '', //成品物资id/设备明细id
                                'issueType': 0, //甲供/发料类型
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'originalConsumptionAmountVarianceAdjustment': 0, //调差原消耗金额
                                'sourceDtlId': '', //源单明细id
                                'spec': e.spec, //规格型号
                                'subItemId': '', //结构部位id
                                'subItemName': '', //结构部位名称
                                'texture': e.texture, //材质
                                'unit': '', //计量单位
                                'warehouseId': '', //仓库id
                                'warehouseName': ''//仓库名称
                            }
                            this.materialsDetailsList.forEach(item=>{
                                item.children.push(obj)
                            })

                        })
                    }else{

                        console.log('val', val)
                        const mapObj = {}
                        let arr = []
                        val.forEach(e => {
                            const children = []
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: 0,
                                    totalQuantity: 0,
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            //  物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                'amountAfterVarianceAdjustment': 0, //调差后金额
                                'billId': this.billid, //物资消耗id
                                'changeType': 1, //变更类型
                                'consumeAmount': e.amount, //消耗金额(元)
                                'consumePrice': 0, //消耗单价(元)
                                'consumeQuantity': e.quantity, //消耗数量
                                'consumeType': 0, //消耗类型
                                'contractId': '', //合同id
                                'contractName': '', //合同名称
                                'cumulativeConsumeQuantity': '', //累计消耗数量
                                'deductionAmount': 0, //扣款金额(元)
                                'deductionQuantity': 0, //扣款数量
                                'designQuantity': 0, //设计数量
                                'dtlId': '', //物资消耗明细id
                                'finishedGoodsDtlId': '', //成品物资id/设备明细id
                                'issueType': 0, //甲供/发料类型
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'originalConsumptionAmountVarianceAdjustment': 0, //调差原消耗金额
                                'sourceDtlId': '', //源单明细id
                                'spec': e.spec, //规格型号
                                'subItemId': '', //结构部位id
                                'subItemName': '', //结构部位名称
                                'texture': e.texture, //材质
                                'unit': '', //计量单位
                                'warehouseId': '', //仓库id
                                'warehouseName': ''//仓库名称

                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.consumeAmount || 0),
                                0
                            )
                            obj.materialName = `小计： ${count}`
                            obj.children = this.uniqueArray(obj.children, 'customId')

                        })
                        this.materialsDetailsList = arr
                    }
                    this.totalCumulativeConsumeQuantity()
                    this.totalconsumeAmount()
                    // this.AllConsumptionAmount()
                })
        },
        //选择销售消耗(现场发料)
        selectSalesConsumption () {

            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/onSiteMaterialIssuance/listUnconsumeSiteIssuanceForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择明细' // 标题
            }).then(val=>{
                this.setSelectedInfo(val)
                val.forEach(item=>{
                    this.basicFormData.subcontractorId = item.pickingUnitId
                    this.basicFormData.subcontractorName = item.pickingUnitName
                    this.getGoods(item.billId)
                })
                //  根据现场发料id在调接口获取物资信息
            })

        },
        //根据选择的现场发料id获取物资
        getGoods (id) {
            this.$Ajax
                .httpGet({
                    url: '/material/onSiteMaterialIssuance/listUnconsumesMaterialByBillIdForSelected',
                    params: {
                        billId: id,
                    },
                }).then(res=>{
                    const mapObj = {}
                    let arr = []
                    res.forEach(e => {
                        const children = []
                        e.materialClassNameArr = e.materialClassName.split('/')
                        e.materialClassIdArr = e.materialClassId.split('/')
                        // TODO: 统计小计
                        let obj
                        const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                        const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                        if (!mapObj[topClassId]) {
                            obj = {
                                topClassId,
                                topClassName,
                                customId: topClassId,
                                materialClassId: topClassId,
                                materialClassName: topClassName,
                                uuid: getUuid(),
                                totalAmount: 0,
                                totalQuantity: 0,
                            }
                            //这里需要改成push多个对象   还没改
                            arr.push(obj)
                            mapObj[topClassId] = obj
                        } else {
                            obj = mapObj[topClassId]
                        }

                        //  物资名称
                        children.push({
                            uuid: getUuid(),
                            customId: getUuid(),
                            'amountAfterVarianceAdjustment': 0, //调差后金额
                            'billId': this.billid, //物资消耗id
                            'changeType': 1, //变更类型
                            'consumeAmount': 0, //消耗金额(元)
                            'consumePrice': 0, //消耗单价(元)
                            'consumeQuantity': e.unconsumeQuantity, //消耗数量
                            'consumeType': 0, //消耗类型
                            'contractId': '', //合同id
                            'contractName': '', //合同名称
                            'cumulativeConsumeQuantity': '', //累计消耗数量
                            'deductionAmount': 0, //扣款金额(元)
                            'deductionQuantity': 0, //扣款数量
                            'designQuantity': 0, //设计数量
                            'dtlId': '', //物资消耗明细id
                            'finishedGoodsDtlId': '', //成品物资id/设备明细id
                            'issueType': 4, //甲供/发料类型
                            'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                            'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                            'materialId': e.materialId, //物资id
                            'materialName': e.materialName, //物资名称
                            'originalConsumptionAmountVarianceAdjustment': 0, //调差原消耗金额
                            'sourceDtlId': '', //源单明细id
                            'spec': e.spec, //规格型号
                            'subItemId': '', //结构部位id
                            'subItemName': '', //结构部位名称
                            'texture': e.texture, //材质
                            'unit': e.unit, //计量单位
                            'warehouseId': e.projectDepartmentWarehouseId, //仓库id
                            'warehouseName': e.projectDepartmentWarehouseName//仓库名称

                        })
                        obj.children = !obj.children
                            ? children
                            : obj.children.concat(children)
                            // 统计小计
                        const count = obj.children.reduce(
                            (prev, c) => (prev += c.unconsumeQuantity || 0),
                            0
                        )
                        obj.materialName = `小计： ${count}`
                        obj.children = this.uniqueArray(obj.children, 'customId')

                    })
                    this.materialsDetailsList = arr

                    this.totalCumulativeConsumeQuantity()
                    this.totalconsumeAmount()
                    // this.AllConsumptionAmount()
                })
        },
        //选择加工销售消耗
        selectProcessSalesConsumption () {
            let ids = []
            let params = []
            params.push(2)
            selectDataClient({
                SelectServiceToken: '/material/processingIssue/listUnconsumeProcessingIssuanceForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(params), //销售合同
                Title: '选择加工发料单' // 标题
            }).then(val=>{
                this.setSelectedInfo(val)
                val.forEach(item=>{
                    this.basicFormData.subcontractorId = item.pickingUnitId
                    this.basicFormData.subcontractorName = item.pickingUnitName
                    this.basicFormData.processingUnitId = item.processingUnitId
                    this.basicFormData.processingUnitName = item.processingUnitName
                    this.getMaterials(item.billId) //获取物资明细
                    this.getProcessMaterials(item.billId) //获取加工成品明细
                })

            })
        },
        //选择消耗盘点(事实合同)
        consumeCheck (businessType) {   //businessType
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/consumptionInventory/listSurplusMaterialSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(businessType),
                Title: '选择明细' // 标题
            }).then(val=>{
                this.setSelectedInfo(val)
                //     openAppClient('/showSelectedData', '选择结果', function () {
                //         // alert('关闭后回调')
                //     })
                // let val = [{ 'amount': null, 'contractId': '1564451257221599233', 'contractName': 'SRBGEHGSL204FBHT019', 'id': '1566275758234202113', 'isDetailed': 1, 'materialClassId': 'a927249830c9-bed9-b74d-792a-c977a13f/5895bbf9-a635-49e3-8639-ca177cd96d18/d04e7391-ce73-41a5-88b6-fdd727381096', 'materialClassName': '机械配件/隧道施工设备/喷浆设备', 'materialId': 'aa1714f09c84-ab3b-b74a-0298-242fbecf', 'materialName': '输料软管', 'parentId': 'a99314ba9846-b76b-bd47-28c6-e91a85c6', 'price': null, 'quantity': 164, 'spec': '5米', 'subcontractorId': 'a99314ba9846-b76b-bd47-28c6-e91a85c6', 'subcontractorName': '四川路达路桥工程有限公司', 'texture': '嘻嘻嘻', 'unit': '根', 'warehouseId': '1564888447634305026', 'warehouseName': '仓库111' }]
                if(this.materialsDetailsList.length > 0) {
                    val.forEach(e=>{

                        e.materialClassNameArr = e.materialClassName.split('/')
                        e.materialClassIdArr = e.materialClassId.split('/')
                        e.materialClassNameArr.shift()
                        e.materialClassIdArr.shift()
                        const p = {
                            'consumeDate': this.basicFormData.consumeDate,
                            'dtls': [
                                {
                                    'materialClassId': e.materialClassIdArr.join('/'),
                                    'materialClassName': e.materialClassNameArr.join('/'),
                                    'materialId': e.materialId,
                                    'materialName': e.materialName,
                                    'spec': e.spec,
                                    'texture': e.texture,
                                    'unit': e.unit
                                }
                            ],
                            'orgId': this.orgId
                        }

                        //获取成本单价
                        let promiseObj  =  new Promise(resolve=>{
                            Api.getMaterialCostUnitPrice(p).then(res=>{
                                res.map(item=>{
                                    item.price
                                })
                                resolve(res)
                            })
                        })
                        promiseObj.then(res=>{
                            res.forEach(a=>{
                                this.consumePrice = a.price
                            })
                            const obj = {
                                uuid: getUuid(),
                                customId: getUuid(),
                                'amountAfterVarianceAdjustment': 0, //调差后金额
                                'billId': this.billid, //物资消耗id
                                'changeType': 1, //变更类型
                                'consumeAmount': 0, //消耗金额(元)
                                'consumePrice': this.consumePrice, //消耗单价(元)
                                'consumeQuantity': e.quantity, //消耗数量
                                'consumeType': 0, //消耗类型
                                'contractId': e.contractId, //合同id
                                'contractName': e.contractName, //合同名称
                                'cumulativeConsumeQuantity': '', //累计消耗数量
                                'deductionAmount': 0, //扣款金额(元)
                                'deductionQuantity': 0, //扣款数量
                                'designQuantity': 0, //设计数量
                                'dtlId': '', //物资消耗明细id
                                'finishedGoodsDtlId': '', //成品物资id/设备明细id
                                'issueType': e.partyAType, //甲供/发料类型
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'originalConsumptionAmountVarianceAdjustment': 0, //调差原消耗金额
                                'sourceDtlId': '', //源单明细id
                                'spec': e.spec, //规格型号
                                'subItemId': '', //结构部位id
                                'subItemName': '', //结构部位名称
                                'texture': e.texture, //材质
                                'unit': e.unit, //计量单位
                                'warehouseId': e.warehouseId, //仓库id
                                'warehouseName': e.warehouseName//仓库名称
                            }
                            this.materialsDetailsList.forEach(item=>{
                                item.children.push(obj)
                            })
                            this.totalconsumeAmount()
                            // this.AllConsumptionAmount()
                            this.totalCumulativeConsumeQuantity()
                        })

                    })
                }else {

                    const mapObj = {}
                    let arr = []
                    val.forEach(e => {
                    //带入分包商信息   getProcessMaterials
                        this.basicFormData.subcontractorId = e.subcontractorId
                        this.basicFormData.subcontractorName = e.subcontractorName
                        const children = []
                        e.materialClassNameArr = e.materialClassName.split('/')
                        e.materialClassIdArr = e.materialClassId.split('/')

                        const p = {
                            'consumeDate': this.basicFormData.consumeDate,
                            'dtls': [
                                {
                                    'materialClassId': e.materialClassIdArr.join('/'),
                                    'materialClassName': e.materialClassNameArr.join('/'),
                                    'materialId': e.materialId,
                                    'materialName': e.materialName,
                                    'spec': e.spec,
                                    'texture': e.texture,
                                    'unit': e.unit
                                }
                            ],
                            'orgId': this.orgId
                        }

                        //获取成本单价
                        let promiseObj  =  new Promise(resolve=>{
                            Api.getMaterialCostUnitPrice(p).then(res=>{
                                res.map(item=>{
                                    item.price
                                })
                                resolve(res)
                            })
                        })
                        promiseObj.then(res=>{   //112233
                            res.forEach(a=>{
                                this.consumePrice = a.price
                            })
                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: 0,
                                    totalQuantity: 0,
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            //  物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                'amountAfterVarianceAdjustment': 0, //调差后金额
                                'billId': this.billid, //物资消耗id
                                'changeType': 1, //变更类型
                                'consumeAmount': 0, //消耗金额(元)
                                'consumePrice': this.consumePrice, //消耗单价(元)
                                'consumeQuantity': e.quantity, //消耗数量
                                'consumeType': 0, //消耗类型
                                'contractId': e.contractId, //合同id
                                'contractName': e.contractName, //合同名称
                                'cumulativeConsumeQuantity': '', //累计消耗数量
                                'deductionAmount': 0, //扣款金额(元)
                                'deductionQuantity': 0, //扣款数量
                                'designQuantity': 0, //设计数量
                                'dtlId': '', //物资消耗明细id
                                'finishedGoodsDtlId': '', //成品物资id/设备明细id
                                'issueType': e.partyAType, //甲供/发料类型
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'originalConsumptionAmountVarianceAdjustment': 0, //调差原消耗金额
                                'sourceDtlId': '', //源单明细id
                                'spec': e.spec, //规格型号
                                'subItemId': '', //结构部位id
                                'subItemName': '', //结构部位名称
                                'texture': e.texture, //材质
                                'unit': e.unit, //计量单位
                                'warehouseId': e.warehouseId, //仓库id
                                'warehouseName': e.warehouseName//仓库名称

                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += Number(c.consumeAmount) || 0),
                                0
                            )
                            obj.materialName = `小计： ${count.toFixed(2)}`
                            obj.children = this.uniqueArray(obj.children, 'customId')

                            this.materialsDetailsList = arr
                            this.totalconsumeAmount()
                            // this.AllConsumptionAmount()
                            this.totalCumulativeConsumeQuantity()
                            this.deductionQuantityAndDeductionAmount()
                        })
                    })
                }

            })
        },
        //选择机械发料
        selectMechanicalStoreIssue () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/mechanicalMaterialIssuance/listSurplusMaterialSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机械发料' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)

                    // let val = [{ 'collectedQuantity': 22, 'consumedQuantity': null, 'equipId': '', 'equipName': '挖挖机', 'equipNumber': 'SRBGWZ001', 'equipSpec': '4', 'materialClassId': 'a92724915394-8f4a-2247-3575-754cb0ea/8366c07b-9a82-4a80-9626-337b2a76a1af/10b8c980-981b-4e90-81b8-550288428a04', 'materialClassName': '其它材料/木材/胶合板', 'materialId': 'a99820331b56-a7a8-0247-4367-1e3a71f7', 'materialName': '胶合板', 'spec': null, 'texture': 'test', 'unconsumedQuantity': null, 'unit': '㎡' }]
                    this.Uids = val.length
                    this.getId()
                    setTimeout(()=>{
                        let arr1 = []
                        val.forEach((e, index)=>{
                            let obj1
                            obj1 = {
                                'billId': this.billid,
                                'changeType': 1,
                                'consumeAmount': 0, //消耗金额(元)
                                'dtlId': this.UidArr[index], //设备明细id
                                'equipId': e.equipId, //设备id
                                'equipName': e.equipName, //设备名称
                                'equipNo': e.equipNumber, //设备编号
                                'remarks': '',
                                'sourceDtlId': '', //源单明细id
                                'spec': e.spec
                            }

                            arr1.push(obj1)

                            this.EquipDtls = arr1
                            //赋值设备子列表
                            const mapObj = {}
                            let arr = []

                            const children = []
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: '',
                                    totalQuantity: '',
                                }
                                arr.push(obj)
                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            // 物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                'amountAfterVarianceAdjustment': 0, //调差后金额
                                'billId': this.billid, //物资消耗id
                                'changeType': 1, //变更类型
                                'consumeAmount': 0, //消耗金额(元)
                                'consumePrice': 0, //消耗单价(元)
                                'consumeQuantity': e.quantity, //消耗数量
                                'consumeType': 0, //消耗类型
                                'contractId': '', //合同id
                                'contractName': '', //合同名称
                                'cumulativeConsumeQuantity': e.consumedQuantity, //累计消耗数量
                                'deductionAmount': 0, //扣款金额(元)
                                'deductionQuantity': 0, //扣款数量
                                'designQuantity': 0, //设计数量
                                'dtlId': '', //物资消耗明细id
                                'finishedGoodsDtlId': obj1.dtlId, //成品物资id/设备明细id    //关联设备明细id
                                'issueType': 5, //甲供/发料类型
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'originalConsumptionAmountVarianceAdjustment': 0, //调差原消耗金额
                                'sourceDtlId': '', //源单明细id
                                'spec': e.spec, //规格型号
                                'subItemId': '', //结构部位id
                                'subItemName': '', //结构部位名称
                                'texture': e.texture, //材质
                                'unit': e.unit, //计量单位
                                'warehouseId': '', //仓库id
                                'warehouseName': ''//仓库名称
                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.designQuantity || 0),
                                0
                            )
                            obj.materialName = `小计： ${count}`
                            obj.children = this.uniqueArray(obj.children, 'customId')

                            this.equipSonTable = arr
                            this.totalCumulativeConsumeQuantity()
                            this.totalconsumeAmount()
                            // this.AllConsumptionAmount()
                            this.equipSonTable.forEach(a=>{
                                a.children.forEach((b, index)=>{
                                    b.finishedGoodsDtlId = this.UidArr[index]
                                })

                            })
                        })

                    }, 500)
                })
        },
        //点击设备编号
        clickEquipNo () {
            this.tableShow = true
        },
        //选择加工发料
        selectProcessReceiving () {
            let ids = []
            let params = []
            params.push(1, 3)
            selectDataClient({
                SelectServiceToken: '/material/processingIssue/listUnconsumeProcessingIssuanceForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(params),  //分包合同 1  事实合同  3
                Title: '选择加工发料单' // 标题
            }).then(val=>{
                this.setSelectedInfo(val)
                //     openAppClient('/showSelectedData', '选择结果', function () {
                //         // alert('关闭后回调')
                //     })
                // let val = [{ 'billId': '1569977502764036097', 'billNo': 'JTGCCYLHXMJGFL20220914001', 'contractBillId': '1560472406476939265', 'contractBillNo': 'JTGCCYLHXMFBHT002', 'contractName': null, 'pickingUnitId': 'a99314b986ef-8e55-e44d-04c6-d0c36194', 'pickingUnitName': '成都石力劳务有限责任公司', 'processingUnitId': '02f0f06d-ee76-4724-9a37-ca9418b8d303', 'processingUnitName': '佛山市顺德区北控科锐再生资源有限公司', 'unconsumeQuantity': 70.2468 }]
                val.forEach(item=>{
                    this.basicFormData.subcontractorId = item.pickingUnitId
                    this.basicFormData.subcontractorName = item.pickingUnitName
                    this.basicFormData.processingUnitId = item.processingUnitId
                    this.basicFormData.processingUnitName = item.processingUnitName
                    this.getMaterials(item.billId) //获取物资明细
                    this.getProcessMaterials(item.billId) //获取加工成品明细
                })
            })
        },
        //加工发料  类型  物资明细
        getMaterials (id) {
            this.$Ajax
                .httpGet({
                    url: '/material/processingIssue/listUnconsumeRawMaterialsByBillIdForSelected',
                    params: {
                        billId: id,
                    },
                }).then(res=>{
                    if(this.materialsDetailsList.length > 0) {
                        res.forEach(e=>{
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            e.materialClassNameArr.shift()
                            e.materialClassIdArr.shift()
                            const obj = {
                                uuid: getUuid(),
                                customId: getUuid(),
                                'amountAfterVarianceAdjustment': e.amountAfterVarianceAdjustment, //调差后金额
                                'billId': this.billid, //物资消耗id
                                'changeType': 1, //变更类型
                                'consumeAmount': 0, //消耗金额(元)    计算：消耗数量*消耗单价，保留2位小数。
                                'consumePrice': this.consumePrice, //消耗单价(元) 通过物资月平均法计算出来的成本单价带入，不可修改
                                'consumeQuantity': e.quantity, //消耗数量 加工发料：带入领料数量，可修改，原物资消耗数量信息根据配合比计算
                                'consumeType': 0, //消耗类型  系统匹配：甲供，超甲供扣款，非甲供扣款。
                                'contractId': '', //合同id
                                'contractName': '', //合同名称
                                'cumulativeConsumeQuantity': '', //累计消耗数量 系统自动计算，消耗数量累加
                                'deductionAmount': 0, //扣款金额(元)
                                'deductionQuantity': 0, //扣款数量
                                'designQuantity': 0, //设计数量  加工发料带入分包合同中设计数量
                                'dtlId': '', //物资消耗明细id
                                'finishedGoodsDtlId': '', //成品物资id/设备明细id
                                'issueType': e.issueType, //甲供/发料类型  加工发料：带入发料中发料类型
                                'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                'materialId': e.materialId, //物资id
                                'materialName': e.materialName, //物资名称
                                'originalConsumptionAmountVarianceAdjustment': e.originalConsumptionAmountVarianceAdjustment, //调差原消耗金额
                                'sourceDtlId': e.dtlId, //源单明细id
                                'spec': e.spec, //规格型号
                                'subItemId': '', //结构部位id
                                'subItemName': '', //结构部位名称 加工发料：带入加工发料“分包合同”中数据
                                'texture': e.texture, //材质
                                'unit': e.unit, //计量单位
                                'warehouseId': '', //仓库id
                                'warehouseName': ''//仓库名称
                            }
                            this.materialsDetailsList.forEach(item=>{
                                item.children.push(obj)
                            })

                        })
                    }else   {

                        const mapObj = {}
                        let arr = []
                        res.forEach(e => {
                            const children = []
                            e.materialClassNameArr = e.materialClassName.split('/')
                            e.materialClassIdArr = e.materialClassId.split('/')
                            //获取成本单价
                            const p = {
                                'consumeDate': this.basicFormData.consumeDate,
                                'dtls': [
                                    {
                                        'materialClassId': e.materialClassIdArr.join('/'),
                                        'materialClassName': e.materialClassNameArr.join('/'),
                                        'materialId': e.materialId,
                                        'materialName': e.materialName,
                                        'spec': e.spec,
                                        'texture': e.texture,
                                        'unit': e.unit
                                    }
                                ],
                                'orgId': this.orgId
                            }
                            //获取成本单价
                            let promiseObj  =  new Promise(resolve=>{
                                Api.getMaterialCostUnitPrice(p).then(res=>{
                                    res.map(item=>{
                                        item.price
                                    })
                                    resolve(res)
                                })
                            })
                            promiseObj.then(res=>{
                                res.forEach(a=>{
                                    this.consumePrice = a.price
                                })
                                // TODO: 统计小计
                                let obj
                                const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                                const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                                if (!mapObj[topClassId]) {
                                    obj = {
                                        topClassId,
                                        topClassName,
                                        customId: topClassId,
                                        materialClassId: topClassId,
                                        materialClassName: topClassName,
                                        uuid: getUuid(),
                                        totalAmount: 0,
                                        totalQuantity: 0,
                                    }
                                    //这里需要改成push多个对象   还没改
                                    arr.push(obj)

                                    mapObj[topClassId] = obj
                                } else {
                                    obj = mapObj[topClassId]
                                }

                                //  物资名称
                                children.push({
                                    uuid: getUuid(),
                                    customId: getUuid(),
                                    'amountAfterVarianceAdjustment': e.amountAfterVarianceAdjustment, //调差后金额
                                    'billId': this.billid, //物资消耗id
                                    'changeType': 1, //变更类型
                                    'consumeAmount': 0, //消耗金额(元)
                                    'consumePrice': this.consumePrice, //消耗单价(元)
                                    'consumeQuantity': e.quantity, //消耗数量
                                    'consumeType': 0, //消耗类型
                                    'contractId': '', //合同id
                                    'contractName': '', //合同名称
                                    'cumulativeConsumeQuantity': '', //累计消耗数量
                                    'deductionAmount': 0, //扣款金额(元)
                                    'deductionQuantity': 0, //扣款数量
                                    'designQuantity': 0, //设计数量  接口无
                                    'dtlId': '', //物资消耗明细id
                                    'finishedGoodsDtlId': '', //成品物资id/设备明细id
                                    'issueType': e.issueType, //甲供/发料类型  接口无
                                    'materialClassId': e.materialClassIdArr.join('/'), //物资类别id
                                    'materialClassName': e.materialClassNameArr.join('/'), //物资类别名称
                                    'materialId': e.materialId, //物资id
                                    'materialName': e.materialName, //物资名称
                                    'originalConsumptionAmountVarianceAdjustment': e.originalConsumptionAmountVarianceAdjustment, //调差原消耗金额
                                    'sourceDtlId': e.dtlId, //源单明细id
                                    'spec': e.spec, //规格型号
                                    'subItemId': '', //结构部位id
                                    'subItemName': '', //结构部位名称
                                    'texture': e.texture, //材质
                                    'unit': e.unit, //计量单位
                                    'warehouseId': '', //仓库id
                                    'warehouseName': ''//仓库名称

                                })
                                obj.children = !obj.children
                                    ? children
                                    : obj.children.concat(children)
                                // 统计小计
                                const count = obj.children.reduce(
                                    (prev, c) => (prev += c.quantity || 0),
                                    0
                                )
                                obj.materialName = `小计： ${count}`
                                obj.children = this.uniqueArray(obj.children, 'customId')
                                this.materialsDetailsList = arr
                                this.totalconsumeAmount()
                                // this.AllConsumptionAmount()
                                this.totalCumulativeConsumeQuantity()
                                this.deductionQuantityAndDeductionAmount()
                            })

                        })
                    }

                })
        },
        //加工发料 类型  加工成品明细
        getProcessMaterials (id) {
            this.$Ajax
                .httpGet({
                    url: '/material/processingIssue/listUnconsumeFinishedGoodsByBillIdForSelected',
                    params: {
                        billId: id,
                    },
                }).then(res=>{
                    const mapObj = {}
                    let arr = []
                    res.forEach(e => {
                        const children = []
                        e.materialClassNameArr = e.materialClassName.split('/')
                        e.materialClassIdArr = e.materialClassId.split('/')

                        const p = {
                            'consumeDate': this.basicFormData.consumeDate,
                            'dtls': [
                                {
                                    'materialClassId': e.materialClassIdArr.join('/'),
                                    'materialClassName': e.materialClassNameArr.join('/'),
                                    'materialId': e.materialId,
                                    'materialName': e.materialName,
                                    'spec': e.spec,
                                    'texture': e.texture,
                                    'unit': e.unit
                                }
                            ],
                            'orgId': this.orgId
                        }
                        // 获取成本单价
                        let promiseObj  =  new Promise(resolve=>{
                            Api.getMaterialCostUnitPrice(p).then(res=>{
                                res.map(item=>{
                                    item.price
                                })
                                resolve(res)
                            })
                        })
                        promiseObj.then(res=>{
                            res.forEach(a=>{
                                this.consumePrice = a.price
                            })

                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: 0,
                                    totalQuantity: 0,
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            //  物资名称
                            children.push({
                                uuid: getUuid(),
                                customId: getUuid(),
                                billId: this.billid, //	物资消耗id
                                changeType: 1, //	变更类型
                                consumeAmount: e.amount, //	消耗金额(元)  计算：消耗数量*消耗单价，保留2位小数。
                                consumePrice: this.consumePrice, //	消耗单价(元)  通过物资月平均法计算出来的成本单价带入，不可修改
                                consumeQuantity: e.unconsumeQuantity, // e.unconsumeQuantity     消耗数量  1、加工发料：带入发料明细中成品明细领料数量，可修改，原物资消耗数量信息根据配合比计算
                                cumulativeConsumeQuantity: e.consumedQuantity, //	累计消耗数量 系统自动计算，消耗数量累加
                                dtlId: '', //成品明细id
                                materialClassId: e.materialClassIdArr.join('/'), //物资类别id(1级类别id/2级类别id/..)
                                materialClassName: e.materialClassNameArr.join('/'), //	物资类别名称(1级类别名称/2级类别名称/..)
                                materialId: e.materialId, //	物资id
                                materialName: e.materialName, //	物资名称
                                sourceFinishedGoodsDtlId: e.dtlId, //源单明细id
                                spec: e.spec, //	规格型号
                                texture: e.texture, //	材质
                                unit: e.unit, //	计量单位
                                warehouseId: e.issuingWarehouseId, //仓库id
                                warehouseName: e.issuingWarehouseName, //	仓库名称
                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.consumedQuantity || 0),
                                0
                            )
                            obj.materialName = `小计： ${count}`
                            obj.children = this.uniqueArray(obj.children, 'customId')
                            this.processDetailsList = arr
                            this.totalconsumeAmount()
                            // this.AllConsumptionAmount()
                            this.totalCumulativeConsumeQuantity()
                            this.deductionQuantityAndDeductionAmount()
                        })

                    })

                    // console.log('dasdasd', this.processDetailsList)
                })
        },
        //根据获取id获取基本信息
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/consume/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    this.basicFormData = res
                })
        },
        //根据加工发料id获取设备明细
        getEquipDtlsById () {
            this.$Ajax
                .httpGet({
                    url: '/material/consume/getEquipDtlsById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    console.log('eeeeeeeeeee', res)
                    if(res == null) {
                        this.EquipDtls  = []
                    }else{
                        this.EquipDtls = res
                    }
                })
        },
        //根据物资消耗id获取原物资明细
        getRawMaterialsListById () {
            this.$Ajax
                .httpGet({
                    url: '/material/consume/getRawMaterialsListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    if(this.basicFormData.businessType === 1 || this.basicFormData.businessType === 7) {
                        console.log('消耗盘点(事实合同)', res)
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })
                        this.materialsDetailsList = res
                    }else if(this.basicFormData.businessType === 2) {
                        console.log('加工发料', res)
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })
                        this.materialsDetailsList = res
                    }else if(this.basicFormData.businessType === 3) {
                        console.log('销售消耗', res)
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })
                        this.materialsDetailsList = res
                    }
                    else if(this.basicFormData.businessType === 4) {
                        console.log('机械发料', res)
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })
                        this.equipSonTable = res
                    }else if(this.basicFormData.businessType === 5) {
                        console.log('账面调差', res)
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })
                        this.materialsDetailsList = res
                    }else if(this.basicFormData.businessType === 6) {
                        console.log('加工销售消耗', res)
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })
                        this.materialsDetailsList = res
                    }

                })
        },
        //根据根据物资消耗id获取成品物资明细
        getFinishedGoodsListById () {
            this.$Ajax
                .httpGet({
                    url: '/material/consume/getFinishedGoodsListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res=>{
                    console.log('res', res)
                    if(this.basicFormData.businessType === 2 || this.basicFormData.businessType === 6) {
                        console.log('成品物资明细>>>>>>', res)
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.children.forEach(i => {
                                i.uuid = i.dtlId
                            })
                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })
                        this.processDetailsList = res
                    }
                })
        },
        //获取历史审核列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '1027',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            }
            CommonApi.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        //生成id
        getId () {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder',
                    params: {
                        num: this.Uids,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                }).then(res=>{
                    res.forEach(item=>{
                        this.UidArr.push(item)
                    })
                })
        },
        //删除提示框
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //根据id删除单据
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/consume/delete',
                    params: {
                        id: this.billid,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel, null, this.cancel)
                    }
                })
        },
        //明细删除
        handleDelete (row, $index) {
            if(row.dtlId) {
                this.$set(row, 'changeType', -1)
            }else{
                this.interiorAllotList.splice($index, 1)

            }
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if(this.materialsDetailsList.length === 0) {
                    let str = '明细不能为空！'
                    this.errorMsg.push(str)
                }
                else  if (this.materialsDetailsList.length > 0) {
                    this.materialsDetailsList.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {
                                if (item.quantity === '' || item.quantity === null) {
                                    let str = `请填写第 ${index + 1} 行的调拨数量`
                                    this.errorMsg.push(str)
                                }
                                if (item.price === '' || item.price === null) {
                                    let str = `请填写第 ${index + 1} 行的采购单价`
                                    this.errorMsg.push(str)
                                }
                                if (item.warehouseName === '' || item.warehouseName === null) {
                                    let str = `请带入第 ${index + 1} 行的发料仓库`
                                    this.errorMsg.push(str)
                                }
                            }
                        })
                    })
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        //监听明细数据input事件
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else{
                row.changeType = 2
            }
            // if(row.designQuantity !== 0) {
            //     if(row.planQuantity > row.designQuantity) {
            //         this.clientPop(
            //             'err',
            //             '计划数量不能超过设计数量!',
            //         )
            //         setTimeout(()=>{
            //             row.planQuantity = row.designQuantity
            //         })
            //     }
            // }

        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        ...mapMutations(['setPopConfirm']),
        //取消
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./consumptionMaterials')
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.dtlId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },

        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },

    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        'basicFormData.redBillState' () {
            if (this.basicFormData.redBillState == '3') {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.basicFormData.redBillState == '0' ||
                this.basicFormData.redBillState == '1'
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.basicFormData.redBillState == '2') {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
        }),
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.basicFormData.redBillState) {
            case '0':
                redState = '冲销中'
                break
            case '1':
                redState = '冲销中'
                break
            case '2':
                redState = '已冲销'
                break
            case '3':
                redState = '红单'
                break
            }
            return redState
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            ['planDetail', 'materialDetails', 'technicalParameter'],
            'accessory',
            'auditHistory',
        ]
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                  prevHeight +
                  document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector('.childTab .el-tabs__nav')
                        ? document.querySelector('.childTab .el-tabs__nav').offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                prevHeight +
                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
        this.scorllDtl()
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
.childTab {
  ::v-deep .el-tabs__header {
    position: absolute !important;
  }
  ::v-deep .el-tabs__content {
    padding: 0 0 0 20px !important;
  }
}
.childTab1 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: fixed;
        top: 0;
        width: 190px;
      }
    }
  }
}
.childTab2 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: absolute;
        bottom: 0;
        width: 100%;
      }
    }
  }
}
</style>